package gnet

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

// GetDate ex:2019-01-14 22:39:50 +0800 CST
type requestST struct {
}

func newRequest() *requestST {
	ptr := &requestST{}
	if ptr.init() {
		return ptr
	} else {
		return nil
	}
}

func (v *requestST) init() bool {
	return true
}

// Get ...
func (v *requestST) Get(url string) map[string]string {
	mp := make(map[string]string)
	mp["result"] = "ok"

	var resp *http.Response
	var err error
	if strings.Index(url, "https") == -1 {
		resp, err = http.Get(url)
	} else {
		tr := &http.Transport{

			TLSClientConfig: &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS12},
		}

		client := &http.Client{Transport: tr}
		resp, err = client.Get(url)
	}

	if err != nil {
		mp["result"] = err.Error()
		return mp
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		mp["result"] = err.Error()
		return mp
	}
	mp["data"] = string(body)
	return mp
}

// 发送POST请求
// url：         请求地址
// data：        POST请求提交的数据
// contentType： 请求体格式，如：application/json
// content：     请求放回的内容
func (v *requestST) Post(url string, data interface{}, contentType string) map[string]string {
	mp := make(map[string]string)
	mp["result"] = "ok"
	// 超时时间：5秒
	client := &http.Client{Timeout: 5 * time.Second}
	jsonStr, _ := json.Marshal(data)
	resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	if err != nil {
		mp["result"] = err.Error()
		return mp
	}
	defer resp.Body.Close()

	result, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		mp["result"] = err.Error()
		return mp
	}

	mp["data"] = string(result)
	return mp
}
